"use strict";
cc._RF.push(module, '4063413ziFJ573EdtZfBjyf', 'Shape');
// Script/Shape.js

'use strict';

var _Board = require('Board');

var _Board2 = _interopRequireDefault(_Board);

var _Config = require('Config');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var getRandomInt = function getRandomInt(min, max) {
  var ratio = Math.random();
  return min + Math.floor((max - min) * ratio);
};
cc.Class({
  extends: cc.Component,

  properties: {
    tileH: 122, // 方块六边形高度
    tileScale: 0.7, // 方块默认缩放值，用于点击后放大效果
    board: {
      // 获取棋盘节点访问
      default: null,
      type: _Board2.default
    },
    // 以下为各方块类型图片
    type1: {
      default: null,
      type: cc.SpriteFrame
    },
    type2: {
      default: null,
      type: cc.SpriteFrame
    },
    type3: {
      default: null,
      type: cc.SpriteFrame
    },
    type4: {
      default: null,
      type: cc.SpriteFrame
    },
    type5: {
      default: null,
      type: cc.SpriteFrame
    },
    type6: {
      default: null,
      type: cc.SpriteFrame
    }
  },

  // LIFE-CYCLE CALLBACKS:

  onLoad: function onLoad() {
    this.setTile();
    this.addTouchEvent();
  },
  setTile: function setTile() {
    var _this = this;

    this.tiles = _Config.Tiles;

    var hexData = this.random();

    var hexPx = hexData.list.map(function (hexArr) {
      return _this.hex2pixel(hexArr, _this.tileH);
    });

    this.setSpriteFrame(hexPx, this['type' + hexData.type]);
    this.node.scale = this.tileScale;
    this.node.ox = this.node.x;
    this.node.oy = this.node.y;
  },
  random: function random() {
    var shape = this.tiles[getRandomInt(0, this.tiles.length)];
    var list = shape.list[getRandomInt(0, shape.list.length)];
    return {
      type: shape.type,
      list: list
    };
  },
  hex2pixel: function hex2pixel(hexArr, h) {
    var size = h / 2;
    var x = size * Math.sqrt(3) * (hexArr[0] + hexArr[1] / 2);
    var y = size * 3 / 2 * hexArr[1];
    return cc.v2(x, y);
  },
  setSpriteFrame: function setSpriteFrame(hexes, tilePic) {
    for (var index = 0; index < hexes.length; index++) {
      var node = new cc.Node('frame');
      var sprite = node.addComponent(cc.Sprite);
      sprite.spriteFrame = tilePic;
      node.x = hexes[index].x;
      node.y = hexes[index].y;
      node.parent = this.node;
    }
  },
  addTouchEvent: function addTouchEvent() {
    var _this2 = this;

    this.node.on('touchstart', function (event) {
      _this2.node.setScale(1);
      _this2.node.children.forEach(function (child) {
        child.setScale(0.8);
      });
      _this2.boardTiles = [];
      _this2.fillTiles = [];
    });
    this.node.on('touchmove', function (event) {
      var _event$touch$getDelta = event.touch.getDelta(),
          x = _event$touch$getDelta.x,
          y = _event$touch$getDelta.y;

      _this2.node.x += x;
      _this2.node.y += y;
      // 方块与棋盘的触碰检测，并返回重合的部分。
      _this2.checkCollision(event);

      if (_this2.checkCanDrop()) {
        _this2.dropPrompt(true);
      } else {
        _this2.dropPrompt(false);
      }
    });
    this.node.on('touchend', function () {
      _this2.tileDrop();
    });
    this.node.on('touchcancel', function () {
      _this2.tileDrop();
    });
  },
  tileDrop: function tileDrop() {
    this.resetBoardFrames();
    if (this.checkCanDrop()) {
      var boardTiles = this.boardTiles;
      var fillTiles = this.fillTiles;
      var fillTilesLength = fillTiles.length;

      for (var i = 0; i < fillTilesLength; i++) {
        var boardTile = boardTiles[i];
        var fillTile = fillTiles[i];
        var fillNode = boardTile.getChildByName('fillNode');
        var spriteFrame = fillTile.getComponent(cc.Sprite).spriteFrame;

        // 棋盘存在方块的标识设置
        boardTile.isFulled = true;
        fillNode.getComponent(cc.Sprite).spriteFrame = spriteFrame;
        // 落子成功后重置方块
        this.resetTile();
      }

      // 这里棋盘需要访问当前方块的六边形总数
      this.board.curTileLength = fillTiles.length;
      // 触发落入成功的事件
      this.board.node.emit('dropSuccess');
    } else {
      this.backSourcePos();
    }
    this.board.checkLose();
  },
  checkLose: function checkLose() {
    var canDropCount = 0;
    var tiles = this.node.children;
    var tilesLength = tiles.length;
    var boardFrameList = this.board.boardFrameList;
    var boardFrameListLength = boardFrameList.length;

    // TODO: 存在无效检测的情况，可优化
    for (var i = 0; i < boardFrameListLength; i++) {
      var boardNode = boardFrameList[i];
      var srcPos = cc.v2(boardNode.x, boardNode.y);
      var count = 0;
      if (!boardNode.isFulled) {
        // 过滤出未填充的棋盘格子
        for (var j = 0; j < tilesLength; j++) {
          var len = 27; // 设定重合判定最小间距

          // 将方块移到未填充的棋盘格子原点，并获取当前各方块坐标值
          var tilePos = srcPos.add(cc.v2(tiles[j].x, tiles[j].y));

          // 遍历棋盘格子，判断方块中各六边形是否可以放入
          for (var k = 0; k < boardFrameListLength; k++) {
            var _boardNode = boardFrameList[k];
            // let dis = cc.pDistance(cc.p(boardNode.x, boardNode.y), tilePos);
            var dis = cc.v2(_boardNode.x, _boardNode.y).sub(tilePos).mag();
            if (dis <= len && !_boardNode.isFulled) {
              count++;
            }
          }
        }

        if (count === tilesLength) {
          canDropCount++;
        }
      }
    }

    if (canDropCount === 0) {
      return true;
    } else {
      return false;
    }
  },
  resetTile: function resetTile() {
    this.node.removeAllChildren();
    this.node.x = this.node.ox;
    this.node.y = this.node.oy;
    this.setTile();
  },
  backSourcePos: function backSourcePos() {
    this.node.scale = this.tileScale;
    this.node.x = this.node.ox;
    this.node.y = this.node.oy;
    this.node.children.forEach(function (child) {
      child.setScale(1);
    });
  },
  checkCollision: function checkCollision(event) {
    var tiles = this.node.children;
    this.boardTiles = []; // 保存棋盘与方块重合部分。
    this.fillTiles = []; // 保存方块当前重合的部分。
    for (var i = 0; i < tiles.length; i++) {
      var tile = tiles[i];
      var pos = this.node.position.add(tile.position);
      var boardTile = this.checkDistance(pos);
      if (boardTile) {
        this.fillTiles.push(tile);
        this.boardTiles.push(boardTile);
      }
    }
  },
  checkDistance: function checkDistance(pos) {
    var distance = 50;
    var boardFrameList = this.board.boardFrameList;
    for (var i = 0; i < boardFrameList.length; i++) {
      var frameNode = boardFrameList[i];
      // const nodeDistance = cc.pDistance(frameNode.position, pos);
      var nodeDistance = frameNode.position.sub(pos).mag();

      if (nodeDistance <= distance) {
        return frameNode;
      }
    }
  },
  checkCanDrop: function checkCanDrop() {
    var boardTiles = this.boardTiles; // 当前棋盘与方块重合部分。
    var fillTiles = this.node.children; // 当前拖拽的方块总数。
    var boardTilesLength = boardTiles.length;
    var fillTilesLength = fillTiles.length;

    // 如果当前棋盘与方块重合部分为零以及与方块数目不一致，则判定为不能落子。
    if (boardTilesLength === 0 || boardTilesLength != fillTilesLength) {
      return false;
    }

    // 如果方块内以及存在方块，则判定为不能落子。
    for (var i = 0; i < boardTilesLength; i++) {
      if (this.boardTiles[i].isFulled) {
        return false;
      }
    }

    return true;
  },
  resetBoardFrames: function resetBoardFrames() {
    var boardFrameList = this.board.boardFrameList;

    for (var i = 0; i < boardFrameList.length; i++) {
      var shadowNode = boardFrameList[i].getChildByName('shadowNode');
      shadowNode.opacity = 0;
    }
  },
  dropPrompt: function dropPrompt(canDrop) {
    var boardTiles = this.boardTiles;
    var boardTilesLength = boardTiles.length;
    var fillTiles = this.fillTiles;

    this.resetBoardFrames();
    if (canDrop) {
      for (var i = 0; i < boardTilesLength; i++) {
        var shadowNode = boardTiles[i].getChildByName('shadowNode');
        shadowNode.opacity = 100;
        var spriteFrame = fillTiles[i].getComponent(cc.Sprite).spriteFrame;
        shadowNode.getComponent(cc.Sprite).spriteFrame = spriteFrame;
      }
    }
  },
  start: function start() {}

  // update (dt) {},

});

cc._RF.pop();